<template>
    <a-form class="smart-query-form" ref="queryFormRef">
      <a-row class="smart-query-form-row">
        <a-form-item label="设备序列号" class="smart-query-form-item">
          <a-input style="width: 300px" v-model:value="queryForm.serialno" placeholder="设备序列号" />
        </a-form-item>
  
        <a-form-item class="smart-query-form-item smart-margin-left10">
          <a-button-group>
            <a-button type="primary" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-form-item>
      </a-row>
    </a-form>
  
    <a-card size="small" :bordered="false">
      <a-row justify="end" ref="tableOperatorRef">
        <TableOperator class="smart-margin-bottom5" v-model="columns" :tableId="TABLE_ID_CONST.DEVICE.TERMINAL" :refresh="ajaxQuery" />
      </a-row>
      <a-table
        size="small"
        :dataSource="tableData"
        :columns="columns"
        bordered
        rowKey="id"
        :pagination="false"
        :loading="tableLoading"
        :scroll="{ y: scrollY }"
      >
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'serialno'">
            <span :class="'text-copy-serialno-' + record.id" :data-clipboard-text="text" @click="textCopy('serialno-' + record.id)">{{ text }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'upstreamId'">
            <span :class="'text-copy-upstreamId-' + record.id" :data-clipboard-text="text" @click="textCopy('upstreamId-' + record.id)">{{ text }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'linkFlag'">
            <template v-if="text">
              <a-tag color="success">在线</a-tag>
            </template>
            <template v-else>
              <a-tag color="error">丢失</a-tag>
            </template>
          </template>
          <template v-else-if="column.dataIndex === 'provinces'">
            <span>{{ (record?.province || '') + record?.city }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'upstreamCode'">
            <span>{{ $smartEnumPlugin.getDescByValue('UPSTREAM_ENUM', text) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'executeStatus'">
            <span>{{ $smartEnumPlugin.getDescByValue('EXECUTE_STATUS_ENUM', text) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'requestStatus'">
            <span>{{ $smartEnumPlugin.getDescByValue('DEVICE_REQUEST_STATUS_ENUM', text) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'operate'">
            <div class="smart-table-operate">
              <a-button type="link" size="small" @click="openRemote(record)">远程终端</a-button>
            </div>
          </template>
        </template>
        
      </a-table>
  
      <div class="smart-query-table-page">
        <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="queryForm.pageSize"
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :total="total"
          @change="ajaxQuery"
          @showSizeChange="ajaxQuery"
          :show-total="(total) => `共${total}条`"
        />
      </div>
    </a-card>
  </template>
  <script setup>
    import { onMounted, onUnmounted, reactive, ref } from 'vue';
    import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
    import { deviceTerminalApi } from '/@/api/device/terminal/device-terminal-api';
    import { smartSentry } from '/@/lib/smart-sentry';
    import TableOperator from '/@/components/support/table-operator/index.vue';
    import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
    import { calcTableHeight } from '/@/lib/table-auto-height';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { message } from 'ant-design-vue';
    import Clipboard from 'clipboard';
  
    const columns = ref([
      {
        title: '设备序列号',
        dataIndex: 'serialno',
        ellipsis: true,
        width: 160,
      },
      {
        title: '上游编号',
        dataIndex: 'upstreamId',
        ellipsis: true,
        width: 200,
      },
      {
        title: '上游',
        dataIndex: 'upstreamCode',
        ellipsis: true,
        width: 80,
      },
      {
        title: '系统类型',
        dataIndex: 'osType',
        width: 75,
      },
      {
        title: '心跳时间',
        dataIndex: 'heartbeatTime',
        width: 160,
      },
      {
        title: '连接状态',
        dataIndex: 'linkFlag',
        width: 75,
      },
      {
        title: 'ip',
        dataIndex: 'ip',
        width: 110,
      },
      {
        title: '省市',
        dataIndex: 'provinces',
        ellipsis: true,
        width: 110,
      },
      {
        title: '运营商',
        dataIndex: 'isp',
        width: 60,
      },
      {
        title: '执行状态',
        dataIndex: 'executeStatus',
        width: 80,
      },
      {
        title: '请求状态',
        dataIndex: 'requestStatus',
        width: 80,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 150,
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        width: 150,
      },
      {
        title: '操作',
        dataIndex: 'operate',
        fixed: 'right',
        width: 250,
      },
    ]);
  
    const queryFormState = {
      serialno: '',
      pageNum: 1,
      pageSize: 10,
    };
    const queryForm = reactive({ ...queryFormState });
    const createDateRange = ref([]);
  
    const tableLoading = ref(false);
    const tableData = ref([]);
    const total = ref(0);
  
    function resetQuery() {
      Object.assign(queryForm, queryFormState);
      createDateRange.value = [];
      ajaxQuery();
    }
  
    function onSearch() {
      queryForm.pageNum = 1;
      ajaxQuery();
    }
  
    async function ajaxQuery() {
      try {
        tableLoading.value = true;
        let responseModel = await deviceTerminalApi.queryList(queryForm);
  
        const list = responseModel.data.list;
        total.value = responseModel.data.total;
        tableData.value = list;
      } catch (e) {
        smartSentry.captureError(e);
      } finally {
        tableLoading.value = false;
      }
    }

    /* 打开远程 web shell 终端 */
    async function openRemote(rowData) {
      SmartLoading.show('正在检查连接状态，请稍等。。。');
      let linkFlag = false;
      try {
        // 检查远程连接状态
        let responseCheck = await deviceTerminalApi.checkRealLink(rowData.serialno);
        linkFlag = responseCheck.data;
      } catch (e) {
        smartSentry.captureError(e);
      } finally {
        setTimeout(() => {
          SmartLoading.hide();
          if (linkFlag) {
            window.open(rowData.remoteUrl, '_blank');
          } else {
            message.warning(`${rowData.serialno}连接丢失，请联系相关人员检查！`, 3);
            ajaxQuery();
          }
        }, 1500)
      }
    }

    // 复制文本
    function textCopy(clzzName) {
      let clipboard = new Clipboard('.text-copy-' + clzzName);
      clipboard.on('success', (e) => {
        message.success('复制成功');
        //  释放内存
        clipboard.destroy();
      });
      clipboard.on('error', (e) => {
        // 不支持复制
        message.error('浏览器不支持复制，请您手动选择复制');
        // 释放内存
        clipboard.destroy();
      });
    }
  
    // ----------------- 表格自适应高度 --------------------
    const scrollY = ref(100);
    const tableOperatorRef = ref();
    const queryFormRef = ref();
  
    function autoCalcTableHeight() {
      calcTableHeight(scrollY, [tableOperatorRef, queryFormRef], 10);
    }
  
    window.addEventListener('resize', autoCalcTableHeight);
  
    onMounted(() => {
      ajaxQuery();
      autoCalcTableHeight();
    });
  
    onUnmounted(() => {
      window.removeEventListener('resize', autoCalcTableHeight);
    });
  </script>
  